/**
 * 
 * Copyright (C) 2011 Cody Stoutenburg . All rights reserved.
 *
 *       This program is free software; you can redistribute it and/or
 *       modify it under the terms of the GNU Lesser General Public License
 *       as published by the Free Software Foundation; either version 2.1
 *       of the License, or (at your option) any later version.
 *
 *       This program is distributed in the hope that it will be useful,
 *       but WITHOUT ANY WARRANTY; without even the implied warranty of
 *       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *       GNU Lesser General Public License for more details.
 *
 *       You should have received a copy of the GNU Lesser General Public License
 *       along with this program; if not, write to the Free Software
 *       Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA. 
 * 
 */
package client.gui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import client.ChatClient;

/**
 * @author Cody Stoutenburg
 * 
 */
public class MainFrame extends JFrame {
	private static final long serialVersionUID = 3005824678586520071L;

	private final ChatClient chat;

	// North
	private JMenuItem itemConnexion;
	private JMenuItem itemDeconnexion;

	// West
	private PanelContactList contactList;

	// Center
	private JTextArea textArea;
	private JTextArea newMessageArea;

	public MainFrame() {
		super("Chat");

		this.setDefaultCloseOperation(EXIT_ON_CLOSE);

		chat = new ChatClient();
		initComponent();

		this.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				quit();
			}
		});

		this.setTitle("chat - " + chat.getServerName());
	}

	private void initComponent() {
		this.getRootPane().setLayout(new BorderLayout());

		// North panel
		JMenuBar menubar = new JMenuBar();

		JMenu menuFichier = new JMenu("Fichier");
		JMenuItem itemQuitter = new JMenuItem("Quitter");
		itemQuitter.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				quit();
			}
		});

		itemConnexion = new JMenuItem("Connexion");
		itemConnexion.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				connect();
			}
		});

		itemDeconnexion = new JMenuItem("Deconnexion");
		itemDeconnexion.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				disconnect();
			}
		});

		menuFichier.add(itemQuitter);
		menuFichier.add(itemConnexion);
		menuFichier.add(itemDeconnexion);

		menubar.add(menuFichier);

		// itemDeconnexion.setVisible(false);

		// West panel
		JPanel panelWest = new JPanel();
		panelWest.setLayout(new BoxLayout(panelWest, BoxLayout.Y_AXIS));
		contactList = new PanelContactList(chat);
		JScrollPane scroll = new JScrollPane(contactList);
		scroll.setPreferredSize(new Dimension(200, 500));

		panelWest.add(scroll);

		// Center panel
		JPanel panelCenter = new JPanel();
		panelCenter.setLayout(new BoxLayout(panelCenter, BoxLayout.Y_AXIS));

		textArea = new JTextArea();
		textArea.setEditable(false);
		textArea.setLineWrap(true);
		textArea.setWrapStyleWord(false);
		JScrollPane panel = new JScrollPane(textArea);
		panel.setPreferredSize(new Dimension(500, 500));

		JPanel panelSendMessage = new JPanel(new FlowLayout());
		panelSendMessage.setBorder(BorderFactory
				.createTitledBorder("Tapez votre message:"));

		newMessageArea = new JTextArea();
		newMessageArea.setLineWrap(true);
		newMessageArea.setWrapStyleWord(false);

		JScrollPane scrollSend = new JScrollPane(newMessageArea,
				JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
				JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		scrollSend.setPreferredSize(new Dimension(500, 50));

		JButton sendMessage = new JButton("Envoyer");
		sendMessage.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				sendMessage();
			}
		});
		panelSendMessage.add(scrollSend);
		panelSendMessage.add(sendMessage);

		panelCenter.add(panel);
		panelCenter.add(panelSendMessage);

		// this.getRootPane().add(menubar, BorderLayout.NORTH);
		this.getRootPane().add(panelWest, BorderLayout.WEST);
		this.getRootPane().add(panelCenter, BorderLayout.CENTER);

		this.pack();
		this.setVisible(true);
	}

	private void quit() {
		if (chat != null) {
			chat.disconnect();
		}
	}

	public void connect() {
		DialogOkCancel<PanelConnexion> dlg = new DialogOkCancel<PanelConnexion>(
				this, "connexion", true, new PanelConnexion());

		dlg.setOkText("Connexion");
		dlg.setCancelText("Annuler");
		dlg.setLayout(FlowLayout.CENTER);
		dlg.setVisible(true);
		if (dlg.getReturnStatus() == DialogOkCancel.RET_OK) {
			String address = dlg.getMainPanel().getAddressIp();
			String port = dlg.getMainPanel().getPort();
			String name = dlg.getMainPanel().getPseudo();

			chat.connect(address, port, name, textArea, contactList);
			this.setTitle("chat - " + chat.getServerName());
		}
	}

	public void disconnect() {
		chat.disconnect();
		this.setTitle("chat - " + chat.getServerName());
	}

	private String getDestinataire() {
		String destinataire = chat.formatDestinataire(contactList
				.getAllContactSelected());
		return destinataire;
	}

	private void sendMessage() {
		String message = newMessageArea.getText();

		if (message.startsWith("!")) {
			Integer nbDes = Integer.valueOf(message.substring(1,
					message.indexOf("d")));

			Integer posPlus = message.indexOf("+");
			Integer des = 0;
			Integer modif = 0;
			if (posPlus > 0) {
				des = Integer.valueOf(message.substring(
						message.indexOf("d") + 1, posPlus));

				modif = Integer
						.valueOf(message.substring(message.indexOf("+") + 1));
			} else {
				des = Integer
						.valueOf(message.substring(message.indexOf("d") + 1));
			}

			System.out.println("ask " + nbDes + "d" + des + "+" + modif);
			chat.askRandom(getDestinataire(), nbDes, des, modif);
		} else {
			chat.sendMessage(getDestinataire(), message);
			textArea.append("vous avez dit: " + message + "\n");
		}
		newMessageArea.setText("");
	}
}
